<template>
  <div class="login-container">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>用户登录</span>
        </div>
      </template>
      <el-form :model="loginForm" status-icon ref="ruleFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router'; // 如果需要在登录后导航到其他页面
import { PostAdminLogin } from '@/api/login';
import { PostErrors } from '@/api/postD';

const router = useRouter();
const ruleFormRef = ref(null);

const loginForm = ref({
  username: '',
  password: ''
});

const submitForm = async () => {
  try {
    const res = await PostAdminLogin(loginForm.value);
    const { code, data,message } = res.data;
    console.log(data,code,message);
    if (code === 200) {
      // 登录成功
      ElMessage.success(message);
      localStorage.setItem('token', data.token);
      localStorage.setItem('user_info', JSON.stringify(data.user_info));
      router.push({name:'home'});
    } else {
      // 登录失败
      PostErrors(error.errors, error.message);
    }

    
    
  } catch (error) {
    // console.error('Error:', error.errors);
    PostErrors(error.errors, error.msg);
  }


};

const resetForm = () => {
  ruleFormRef.value.resetFields();
};

const checkLogin = () => {
 if (localStorage.getItem('admin')) {
     router.push({name:'home'})
     ElMessage.success('已登录，跳转中...')
 }
};
onMounted(() => {
  checkLogin()
});

</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.box-card {
  width: 480px;
}
</style>